import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_api/widgets/title_text_container.dart';

// 表单
class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(12.0),
      child: ListView(
        children: [
          TitleTextContainer(
            '单独使用TextFiled',
            child: TextFiledWidget(),
          ),
          TitleTextContainer(
            '表单组件(Form)',
            child: FormWidget(),
          ),
        ],
      ),
    );
  }
}

// 但是使用TextField，不使用表单
// 无法对用户输入的字段做较好的判断（如用户不输入内容直接登录）
class TextFiledWidget extends StatefulWidget {
  @override
  _TextFiledWidgetState createState() => _TextFiledWidgetState();
}

class _TextFiledWidgetState extends State<TextFiledWidget> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        UsernameTextField(),
        PasswordTextFiled(),
      ],
    );
  }
}

TextEditingController usernameController = TextEditingController();
TextEditingController passwordController = TextEditingController();
// 改变键盘右下角图标以及动作
FocusNode passwordNode = FocusNode();

class UsernameTextField extends StatefulWidget {
  @override
  _UsernameTextFieldState createState() => _UsernameTextFieldState();
}

class _UsernameTextFieldState extends State<UsernameTextField> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: Theme(
        // 更改选中的颜色
        data: ThemeData(primaryColor: Colors.amber),
        child: TextField(
          // 进入页面直接弹出键盘
          autofocus: true,
          // 一次性获取文本内从
          controller: usernameController,
          // 监听输入框文本变化
          onChanged: (value) {
            print('username change:$value');
          },
          // 输入类型
          keyboardType: TextInputType.emailAddress,
          // 改变键盘右下角按钮样式
          textInputAction: TextInputAction.next,
          // 编辑完成，点击右下角按钮跳转到密码输入框passwordNode
          onEditingComplete: () =>
              FocusScope.of(context).requestFocus(passwordNode),
          decoration: InputDecoration(
            labelText: '用户名',
            hintText: '请输入正确的用户名',
            border: OutlineInputBorder(),
            // 输入框填充颜色
            filled: true,
            fillColor: Colors.grey[350],
            prefixIcon: Icon(Icons.person),
          ),
        ),
      ),
    );
  }
}

class PasswordTextFiled extends StatefulWidget {
  @override
  _PasswordTextFiledState createState() => _PasswordTextFiledState();
}

class _PasswordTextFiledState extends State<PasswordTextFiled> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: TextField(
        controller: passwordController,
        maxLength: 6,
        // 设置最大长度为6，当超过6位的行为
        maxLengthEnforcement: MaxLengthEnforcement.enforced,
        // 隐藏文本，密码样式
        obscureText: true,
        textInputAction: TextInputAction.done,
        focusNode: passwordNode,
        onSubmitted: (content) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text(
                  'username=${usernameController.text},password=${passwordController.text}')));
        },
        decoration: InputDecoration(
            // 去除边框
            border: InputBorder.none,
            labelText: '密码',
            hintText: '请输入密码',
            prefixIcon: Icon(Icons.lock)),
      ),
    );
  }
}

// 使用表单组件，优雅的实现一次性校验、重置输入框
class FormWidget extends StatefulWidget {
  @override
  _FormWidgetState createState() => _FormWidgetState();
}

class _FormWidgetState extends State<FormWidget> {
  // 表单全局key，可以绑定一个表单，并获取表单状态
  GlobalKey<FormState> formGlobalKey = GlobalKey<FormState>();

  String _username;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('username=$_username'),
        Form(
          key: formGlobalKey,
          child: TextFormField(
            decoration: InputDecoration(labelText: '姓名', hintText: '请输入姓名'),
            // 表单验证
            validator: (content) {
              if (content.length < 4) {
                return '至少4位';
              }
              return null;
            },
            onSaved: (content) {
              setState(() {
                _username = content;
              });
            },
          ),
        ),
        Container(
          width: double.infinity,
          child: ElevatedButton(
            child: Text('登录'),
            onPressed: _save,
          ),
        )
      ],
    );
  }

  void _save() {
    var form = formGlobalKey.currentState;
    // 验证表单,验证逻辑在每个输入框中
    if (form.validate()) {
      // 保存表单值，具体逻辑在每个表单中
      form.save();
    } else {
      form.reset(); // 验证失败，清空表单
    }
  }
}
